<template>
  <div class="login-container">
    <h2 class="login-title">{{ loginTitle }}</h2>

    <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        status-icon
        class="login-form"
    >
      <!-- 账号登录 -->
      <template v-if="activeType === 'account'">
        <el-form-item label="账号" prop="account">
          <el-input v-model="form.account" placeholder="请输入账号" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
              v-model="form.password"
              placeholder="请输入密码"
              type="password"
          />
        </el-form-item>
        <el-form-item prop="captcha">
          <el-input v-model="form.captcha" placeholder="请输入验证码">
            <template #suffix>
              <img :src="captchaImage" class="captcha-img"  alt="验证码" @click="refreshCaptcha"/>
            </template>
          </el-input>
        </el-form-item>
      </template>

      <!-- 手机登录 -->
      <template v-else-if="activeType === 'phone'">
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item prop="smsCode">
          <el-input v-model="form.smsCode" placeholder="请输入验证码">
            <template #suffix>
              <el-button :disabled="btnTime" type="primary" @click="sendCode">{{btnText}}</el-button>
            </template>
          </el-input>
        </el-form-item>
      </template>

      <!-- 邮箱登录 -->
      <template v-else-if="activeType === 'email'">
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item prop="emailCode">
          <el-input v-model="form.emailCode" placeholder="请输入验证码">
            <template #suffix>
              <el-button :disabled="btnTime2" type="primary" @click="sendEmailCode">{{btnText2}}</el-button>
            </template>
          </el-input>
        </el-form-item>
      </template>

      <!-- 登录按钮 -->
      <div class="login-actions">
        <div class="login-btn" @click="submitForm">
          <img src="/src/assets/login_enter.png" class="login-btn-img" alt="" />
          <div class="login-btn-text">登录</div>
        </div>
      </div>

      <!-- 登录方式 -->
      <div class="login-tabs">
        <div
            class="login-tab"
            v-for="type in loginTypes"
            :key="type.value"
            :class="{ active: activeType === type.value }"
            @click="activeType = type.value"
        >
          <img :src="type.icon" class="tab-icon" />
          <div class="tab-label">{{ type.label }}</div>
        </div>
      </div>

      <!-- 注册链接 -->
      <div class="register-link">
        没有账号？<a href="/register">点我注册</a>
      </div>
    </el-form>
  </div>
</template>

<script setup>
import {reactive, ref, computed, watch, onMounted} from 'vue'
import { ElMessage } from 'element-plus'
import axios from "axios";
import {userStore} from "@/store/index.js";
import {router} from "@/router/index.js";
import pako from 'pako';

const store = userStore();

// 表单引用
const formRef = ref(null)

// 当前激活登录类型
const activeType = ref('account')

// 表单数据
const form = ref({
  account: '',
  password: '',
  captcha: '',
  phone: '',
  smsCode: '',
  email: '',
  emailCode: '',
})

// 校验规则
const rules = {
  account: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 4, max: 6, message: '验证码长度应为4~6位', trigger: 'blur' },
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: '请输入有效的手机号',
      trigger: 'blur',
    },
  ],
  smsCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 4, max: 6, message: '验证码长度应为4~6位', trigger: 'blur' },
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    {
      type: 'email',
      message: '请输入有效的邮箱地址',
      trigger: ['blur', 'change'],
    },
  ],
  emailCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 4, max: 6, message: '验证码长度应为4~6位', trigger: 'blur' },
  ],
}

// 登录方式切换
const loginTypes = [
  {
    label: '账号登录',
    value: 'account',
    icon: '/src/assets/login_account.png',
  },
  {
    label: '手机登录',
    value: 'phone',
    icon: '/src/assets/login_mobile.png',
  },
  {
    label: '邮箱登录',
    value: 'email',
    icon: '/src/assets/login_email.png',
  },
]

// 登录标题计算属性
const loginTitle = computed(() => {
  switch (activeType.value) {
    case 'account':
      return '账号密码登录'
    case 'phone':
      return '手机号登录'
    case 'email':
      return '邮箱登录'
    default:
      return ''
  }
})

//封装要传递到后端的账户登录数据
const account_key = ref();
// 工具函数：解析 JWT 的 payload 部分


function parseGzipJwt(token) {
  try {
    const base64Url = token.split('.')[1];
    const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
    const compressedPayload = Uint8Array.from(atob(base64), c => c.charCodeAt(0));
    const json = pako.ungzip(compressedPayload, { to: 'string' });
    return JSON.parse(json);
  } catch (e) {
    console.error('GZIP JWT 解析失败：', e);
    return {};
  }
}


// 提交表单
function submitForm() {
  formRef.value.validate((valid) => {
    if (valid) {
      let payload;
      let requestUrl = '';

      if (activeType.value === 'account') {
        payload = {
          username: form.value.account,
          password: form.value.password,
          code: form.value.captcha,
          key: account_key.value,
        };
        requestUrl = "/user/login";

      } else if (activeType.value === 'phone') {
        payload = {
          phone: form.value.phone,
          code: form.value.smsCode,
        };
        requestUrl = "/user/telLogin";

      } else if (activeType.value === 'email') {
        payload = {
          email: form.value.email,
          code: form.value.emailCode,
        };
        requestUrl = "/user/emailLogin";
      }

      axios.post(requestUrl, payload).then(resp => {
        if (resp.status === 200) {

          const token = resp.headers['authorization']; // 获取 token
          if (token) {
            localStorage.setItem('token', token); // 可选：持久化
            const claims = parseGzipJwt(token); // 解析出 payload
            console.log("claims.permissions.values"+claims.permissions)


            store.updatePermissions(claims.permissions); // ✅ 权限存入 Pinia
            store.updateUser(resp.data); // 用户基本信息
            store.updateLoginStatus(true);
          }
          router.push("/")

          ElMessage.success('登录成功！');
          console.log("pina====>" + store.permissions)

        }
      }).catch(error => {
        ElMessage.error(error.response?.data || "登录失败");
      });

    } else {
      ElMessage.error('请填写完整信息');
    }
  });
}


// 登录功能实现开始
//获取图形验证码
const captchaImage = ref('')

const fetchCaptcha = () => {
  axios.get("user/fetchCaptcha").then(resp => {
    captchaImage.value = resp.data.code;//后端传过来的图片验证码，
    account_key.value = resp.data.key;//后端传过来的key，存在于缓存中，用于登录时验证输入的图片验证码是否正确
  })
}
onMounted( () => {
  fetchCaptcha();
})
const refreshCaptcha = () => {
  fetchCaptcha();
}
//监听如果当前的登录方式是账户登录，向后台发起获取验证码请求
watch(activeType, (newType) => {
  //当登录方式切换的时候，清空表单中填入的数据
  form.value = {
    account: '',
    password: '',
    captcha: '',
    phone: '',
    smsCode: '',
    email: '',
    emailCode: '',
  };
  if (newType === 'account') {
    fetchCaptcha();
  }
})
//获取手机验证码
//发送验证码请求
//发送验证码按钮控制
const btnTime = ref(false);
//按钮文本
const btnText = ref("发送验证码");
const sendCode = () =>{
  const payload = {
    phone: form.value.phone,
  }
  formRef.value.validateField('phone',(valid) => {
    if (valid) {
      axios.get(`/user/sendTelCode/${form.value.phone}`).then(resp => {
        ElMessage.success(resp.data);
      }).catch(error => {
        ElMessage.error(error.response.data)
      }).finally(() => {
        btnTime.value = true;

        let seconds = 15;

        const timers = setInterval( () => {
          seconds--;
          if(seconds > 0){
            btnText.value = `${seconds}后重新发送`;
          }else{
            btnTime.value = false;
            btnText.value = "发送验证码"
            clearInterval(timers);
          }
        },1000)
      })
    } else {
      ElMessage.warning('请输入正确格式的手机号')
    }
  })
}

//发送验证码按钮控制
const btnTime2 = ref(false);
//按钮文本
const btnText2 = ref("发送验证码");
//获取邮箱验证码
const sendEmailCode = () =>{
  const payload = {
    phone: form.value.email,
  }
  formRef.value.validateField('email',(valid) => {
    if (valid) {
      axios.get(`/user/getEmailCode4Login/${form.value.email}`).then(resp => {
        ElMessage.success(resp.data);
      }).catch(error => {
        ElMessage.error(error.response.data)
      }).finally(() => {
        btnTime2.value = true;

        let seconds = 15;

        const timers = setInterval( () => {
          seconds--;
          if(seconds > 0){
            btnText2.value = `${seconds}后重新发送`;
          }else{
            btnTime2.value = false;
            btnText2.value = "发送验证码"
            clearInterval(timers);
          }
        },1000)
      })
    } else {
      ElMessage.warning('请输入正确格式的邮箱')
    }
  })
}
</script>

<style scoped>
.login-container {
  width: 400px;
  margin: 60px auto;
  padding: 32px;
  background: #f9f9f9;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
}
.login-title {
  text-align: center;
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 20px;
}
.login-form :deep(.el-form-item) {
  display: flex;
  align-items: center;
}
.login-form :deep(.el-form-item .el-input) {
  flex: 1;
}
.captcha-img {
  width: 80px;
  height: 32px;
  object-fit: contain;
  cursor: pointer;
  margin-left: 8px;
}
.login-tabs {
  display: flex;
  justify-content: center;
  gap: 24px;
  margin-top: 20px;
}
.login-tab {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  transition: all 0.2s;
}
.login-tab.active .tab-icon {
  border: 2px solid #409eff;
  border-radius: 50%;
}
.tab-icon {
  width: 40px;
  height: 40px;
  margin-bottom: 4px;
}
.tab-label {
  font-size: 12px;
}
.login-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}
.login-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
}
.login-btn-img {
  width: 40px;
  height: 40px;
}
.login-btn-text {
  font-size: 12px;
  margin-top: 4px;
  color: #409eff;
}
.register-link {
  text-align: center;
  margin-top: 12px;
  font-size: 13px;
}
.register-link a {
  color: #409eff;
}
</style>
